package org.zjx.app.task;

import org.zjx.app.commnad.ICommand;
import org.zjx.app.commnad.impl.ExitCommand;
import org.zjx.app.task.tasks.CatchGhostsTask;
import org.zjx.app.task.tasks.DivisionTask;
import org.zjx.command.entity.Quest;
import org.zjx.command.state.AccountState;
import org.zjx.command.state.StateManager;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskManager {
    public static Map<String, List<Task>> taskMap = new ConcurrentHashMap<>();

    private static final class InstanceHolder {
        static final TaskManager instance = new TaskManager();
    }

    public static TaskManager getInstance() {
        return InstanceHolder.instance;
    }

    public ICommand getCommand(StateManager stateManager) {
        AccountState accountState = stateManager.getState(AccountState.class);
        if (!taskMap.containsKey(accountState.getPlayerId())) addTask(accountState);
        Task task = taskMap.get(accountState.getPlayerId()).stream()
                .filter(t -> !t.isCompleted())
                .findFirst()
                .orElse(null);
        if (task == null) {
            //任务执行完成，退出游戏
            return new ExitCommand();
        }
        return task.getCommand(stateManager);
    }

    private void addTask(AccountState accountState) {
        taskMap.put(accountState.getPlayerId(), Arrays.asList(new DivisionTask(accountState.getSect()),new CatchGhostsTask()));
//        taskMap.put(roleState.getPlayerId(), Collections.singletonList(new CatchGhostsTask()));
    }

    public void complete(String playerId, Quest quest) {
        List<Task> tasks = taskMap.get(playerId);
        if (tasks == null || quest == null) return;
        for (Task task : tasks) {
            task.complete(quest);
        }
    }
}
